<?php

function wptovp_publish_md_page($post_ID, $post, $update)
{

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }

    if ($post->post_status == 'auto-draft' || wp_is_post_revision($post_ID)) {
        return;
    }

	$categories = wptovp_get_post_categories($post_ID);

	$title = $post->post_title;
	$content = $post->post_content;
	$permalink = $post->post_name;
	$formulated_content = "# ".$title."\n\n".$content;

	if(!empty($categories)){
		foreach($categories as $cat){
			$cat_name = $cat['name'];
            $cat_id = $cat['id'];

			if($cat_id == 1){
				$file = wp_to_vp_plugin_path.'vitepress/docs/'.$permalink.'.md';
				if(!file_exists($file)){
					$file_handle = fopen($file, 'a');
					fwrite($file_handle, $formulated_content);
					fclose($file_handle);
				}

				if(file_exists($file) && $update){
					unlink($file);
					$file_handle = fopen($file, 'a');
					fwrite($file_handle, $formulated_content);
					fclose($file_handle);
				}
			}

			if($cat_id !== 1){
				if(!is_dir(wp_to_vp_plugin_path.'vitepress/docs/'.$cat_name)){
					mkdir(wp_to_vp_plugin_path.'vitepress/docs/'.$cat_name);
				}
				$file = wp_to_vp_plugin_path.'vitepress/docs/'.$cat_name."/".$permalink.'.md';

				if(!file_exists($file)){
					$file_handle = fopen($file, 'a');
					fwrite($file_handle, $formulated_content);
					fclose($file_handle);
				}

				if(file_exists($file) && $update){
					unlink($file);
					$file_handle = fopen($file, 'a');
					fwrite($file_handle, $formulated_content);
					fclose($file_handle);
				}
			}

		}
	}

}

add_action('save_post', 'wptovp_publish_md_page', 10, 3);

function wptovp_delete_post($post_ID){
    $permalink = get_post($post_ID)->post_name;

	$categories = wptovp_get_post_categories($post_ID);

	if(!empty($categories)){
		foreach($categories as $cat){
            $cat_name = $cat['name'];
            $cat_id = $cat['id'];

            if($cat_id == 1){
                $file = wp_to_vp_plugin_path.'vitepress/docs/'.$permalink.'.md';
                unlink($file);
            }

            if($cat_id!== 1){
                $file = wp_to_vp_plugin_path.'vitepress/docs/'.$cat_name."/".$permalink.'.md';
                unlink($file);
            }
        }
	}
}

add_action('wp_trash_post', 'wptovp_delete_post');